// 全局路由守卫
import { createRouter, createWebHistory } from 'vue-router'
import { ElNotification } from 'element-plus'
import NProgress from '@/plugins/nprogress'
import { AuthStore } from '@/stores/modules/auth'
import { staticRouter, errorRouter } from '@/router/menus'
import getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...staticRouter, ...errorRouter],
})

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, _from, next) => {
  // 页面加载进度条
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title as string)

  const authStore = AuthStore()

  authStore.setNav({
    path: to.path,
    query: to.query,
  })

  const token = getToken() || localStorage.getItem('access_token') //登录标示
  const login = authStore.login //store登录状态

  if (to.meta.open == true) {
    next()
  } else {
    if (login && token) {
      next()
    } else {
      // console.time("time");
      // console.log("路由载入中...");
      const res = await authStore.updatePerms()
      if (res) {
        next({
          ...to,
          replace: true,
        })
      } else {
        next(`/account/login?redirect=${to.path}`)
      }
    }
  }
})

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
  NProgress.done()
})

/**
 * @description 路由跳转错误
 * */
router.onError((error) => {
  NProgress.done()
  ElNotification.error({ title: '路由错误', message: error.message })
})

export default router
